package util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encoder {

    private Encoder() {}

    /**
     * 加密效果和 PHP 相同
     * @param str
     * @param algorithm
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static String encode(String str, String algorithm) throws NoSuchAlgorithmException {

        // Create MD5 Hash
        MessageDigest digest = MessageDigest.getInstance(algorithm);

        digest.update(str.getBytes());

        byte[] messageDigest = digest.digest();

        // Create Hex String
        StringBuilder hexString = new StringBuilder();

        for (int i = 0; i < messageDigest.length; i++) {
            hexString.append(String.format("%02x", 0xFF & messageDigest[i]));
        }

        return hexString.toString();
    }

    /**
     * 加密效果和 PHP 相同
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encodeMD5(String str) throws NoSuchAlgorithmException {
        return encode(str, "MD5");
    }

    /**
     * 加密效果和 PHP 相同
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encodeSHA1(String str) throws NoSuchAlgorithmException {
        return encode(str, "SHA-1");
    }
}